package com.paranoid.flashcard.dao;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;

public class FileSystemCache {
	
	private final static String CACHE_DIR = "/quizlet/data"; 
	private File mPictureDir;
	
	public FileSystemCache() {
		File sdcard = Environment.getExternalStorageDirectory();
		mPictureDir = new File(sdcard, CACHE_DIR);
		if (!mPictureDir.exists())
			mPictureDir.mkdirs();
	}

	public boolean saveCardImage(long deckId, long cardId, byte[] image) {
		if (image == null) {
			return true;
		}
	    File deckImageDir = new File(mPictureDir, ""+deckId);
	    if (!deckImageDir.exists()) {
	    	deleteDirectory(deckImageDir);
	    }
	    deckImageDir.mkdirs();
		File imageFile = getImageFile(deckId, cardId);
		try {
			imageFile.createNewFile();
			OutputStream out = new FileOutputStream(imageFile);
			out.write(image);
			out.close();
		} catch (IOException ex) {
			Log.e("", "File error" + ex.getMessage(), ex);
		}
	    
		return true;
	}
	
	
	public boolean deleteDeck(long deckId) {
	    File deckImageDir = new File(mPictureDir, ""+deckId);
	    return deleteDirectory(deckImageDir);
	}

	
	public Bitmap getImage(long deckId, long cardId) {
		File image = getImageFile(deckId, cardId);
		if (image.exists())
			return BitmapFactory.decodeFile(image.getAbsolutePath());
		else
			return null;
	}
	
	
	private File getImageFile(long deckId, long cardId) {
		return new File(new File(mPictureDir, ""+deckId), ""+cardId + ".jpg");
	}
	
	
	private static boolean deleteDirectory(File path) {
		if (path.exists()) {
			File[] files = path.listFiles();
			for (File file : files) {
				if (file.isDirectory()) {
					deleteDirectory(file);
				} else {
					file.delete();
				}
			}
		}
		return path.delete();
	}
}
